package com.smartwebx.fr.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Objects;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import com.google.common.base.Strings;

public class JSUtil {

	private static ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");

	static {
		URL path = JSUtil.class.getResource("/../../resources/myjs/dateUtil.js");
		InputStreamReader isr = null;
		try {
			isr = new InputStreamReader(new FileInputStream(path.getPath()), "UTF-8");
			BufferedReader read = new BufferedReader(isr);
			engine.eval(read);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String execute(String script) {
		String result = null;
		if (!Strings.isNullOrEmpty(script)) {
			try {
				Invocable in = (Invocable) engine;
				Object obj = in.invokeFunction("javaCallFun", script);
				result = Objects.toString(obj, "脚本错误");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}
}